<template>
  <div class="supplier-form">
    <el-form
      ref="supplierForm"
      :model="form"
      :rules="rules"
      label-width="120px"
      class="form-container"
    >
      <el-form-item label="供应商名称" prop="supplierName">
        <el-input
          v-model="form.supplierName"
          placeholder="请输入供应商名称"
          clearable
          class="form-input"
        />
      </el-form-item>

      <el-form-item label="联系人" prop="contactName">
        <el-input
          v-model="form.contactName"
          placeholder="请输入联系人姓名"
          clearable
          class="form-input"
        />
      </el-form-item>

      <el-form-item label="联系电话" prop="contactPhone">
        <el-input
          v-model="form.contactPhone"
          placeholder="请输入联系电话"
          clearable
          class="form-input"
        />
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input
          v-model="form.email"
          placeholder="请输入邮箱地址"
          clearable
          class="form-input"
        />
      </el-form-item>

      <el-form-item label="地址" prop="address">
        <el-input
          v-model="form.address"
          placeholder="请输入地址"
          clearable
          class="form-input"
        />
      </el-form-item>

      <el-form-item label="备注" prop="remarks">
        <el-input
          v-model="form.remarks"
          type="textarea"
          :rows="4"
          placeholder="请输入备注信息"
          class="form-textarea"
        />
      </el-form-item>
    </el-form>

    <!-- 表单操作按钮 -->
    <div class="form-actions">
      <el-button @click="handleCancel" class="cancel-btn">
        返回
      </el-button>
      <el-button 
        type="primary" 
        @click="handleSubmit" 
        :loading="submitting"
        class="submit-btn"
      >
        保存
      </el-button>
    </div>
  </div>
</template>

<script>
import { supplierApi } from '@/api/supplier'

export default {
  name: 'SupplierForm',
  props: {
    formData: {
      type: Object,
      default: () => ({})
    },
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      form: {
        supplierId: '',
        supplierName: '',
        contactName: '',
        contactPhone: '',
        email: '',
        address: '',
        remarks: ''
      },
      submitting: false,
      rules: {
        supplierName: [
          { required: true, message: '请输入供应商名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        contactName: [
          { required: true, message: '请输入联系人姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        contactPhone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入地址', trigger: 'blur' },
          { min: 5, max: 100, message: '长度在 5 到 100 个字符', trigger: 'blur' }
        ],
        remarks: [
          { required: false, message: '请输入备注信息', trigger: 'blur' },
          { max: 200, message: '备注不能超过 200 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    formData: {
      handler(newVal) {
        if (newVal && Object.keys(newVal).length > 0) {
          this.form = { ...newVal }
        } else {
          this.resetForm()
        }
      },
      immediate: true,
      deep: true
    },
    isEdit: {
      handler(newVal) {
        // 当切换到新增模式时，生成供应商ID
        if (!newVal) {
          this.generateSupplierId()
        }
      },
      immediate: true
    }
  },
  mounted() {
    // 如果是新增模式，生成供应商ID
    if (!this.isEdit) {
      this.generateSupplierId()
    }
  },
  methods: {
    // 生成供应商ID
    async generateSupplierId() {
      try {
        const response = await supplierApi.generateSupplierId()
        if (response.code === 200) {
          this.form.supplierId = response.data
        } else {
          // 如果后端生成失败，使用时间戳作为备用方案
          this.form.supplierId = 'SP' + Date.now()
        }
      } catch (error) {
        console.error('生成供应商ID失败:', error)
        // 使用时间戳作为备用方案
        this.form.supplierId = 'SP' + Date.now()
      }
    },

    // 重置表单
    resetForm() {
      this.form = {
        supplierId: '',
        supplierName: '',
        contactName: '',
        contactPhone: '',
        email: '',
        address: '',
        remarks: ''
      }
      this.$nextTick(() => {
        this.$refs.supplierForm.clearValidate()
      })
    },

    // 提交表单
    async handleSubmit() {
      const valid = await this.$refs.supplierForm.validate()
      if (valid) {
        this.submitting = true
        try {
          // 如果是新增模式且没有supplierId，先生成ID
          if (!this.isEdit && !this.form.supplierId) {
            await this.generateSupplierId()
          }
          
          console.log('SupplierForm 提交的表单数据:', this.form)
          console.log('SupplierForm supplierId:', this.form.supplierId)
          
          // 确保supplierId存在
          if (!this.form.supplierId) {
            this.form.supplierId = 'SP' + Date.now()
            console.log('使用备用ID:', this.form.supplierId)
          }
          
          // 发送表单数据给父组件
          this.$emit('submit', { ...this.form })
        } catch (error) {
          this.$message.error('提交失败: ' + error.message)
        } finally {
          this.submitting = false
        }
      } else {
        this.$message.warning('请完善表单信息')
      }
    },

    // 取消表单
    handleCancel() {
      this.$emit('cancel')
    }
  }
}
</script>

<style scoped>
.supplier-form {
  padding: 20px 0;
}

.form-container {
  max-width: 100%;
}

.form-input {
  width: 100%;
}

.form-input .el-input__inner {
  border-radius: 6px;
  border: 1px solid #dcdfe6;
  transition: border-color 0.3s;
}

.form-input .el-input__inner:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.form-textarea {
  width: 100%;
}

.form-textarea .el-textarea__inner {
  border-radius: 6px;
  border: 1px solid #dcdfe6;
  transition: border-color 0.3s;
  resize: vertical;
  min-height: 100px;
}

.form-textarea .el-textarea__inner:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

/* 表单项样式 */
.el-form-item {
  margin-bottom: 24px;
}

.el-form-item__label {
  font-weight: 600;
  color: #606266;
  line-height: 40px;
}

.el-form-item__content {
  line-height: 40px;
}

/* 表单操作按钮样式 */
.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px 0;
  border-top: 1px solid #e4e7ed;
  margin-top: 20px;
}

.cancel-btn {
  padding: 12px 24px;
  border-radius: 6px;
  border: 1px solid #dcdfe6;
  background-color: #fff;
  color: #606266;
  transition: all 0.3s;
}

.cancel-btn:hover {
  color: #409eff;
  border-color: #c6e2ff;
  background-color: #ecf5ff;
}

.submit-btn {
  padding: 12px 24px;
  border-radius: 6px;
  background-color: #409eff;
  border-color: #409eff;
  transition: all 0.3s;
}

.submit-btn:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

.submit-btn:active {
  background-color: #3a8ee6;
  border-color: #3a8ee6;
}

/* 表单验证错误样式 */
.el-form-item.is-error .el-input__inner,
.el-form-item.is-error .el-textarea__inner {
  border-color: #f56c6c;
}

.el-form-item.is-error .el-input__inner:focus,
.el-form-item.is-error .el-textarea__inner:focus {
  border-color: #f56c6c;
  box-shadow: 0 0 0 2px rgba(245, 108, 108, 0.2);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .supplier-form {
    padding: 10px 0;
  }
  
  .el-form-item {
    margin-bottom: 20px;
  }
  
  .el-form-item__label {
    line-height: 32px;
    font-size: 14px;
  }
  
  .el-form-item__content {
    line-height: 32px;
  }
  
  .form-actions {
    flex-direction: column;
    gap: 8px;
  }
  
  .cancel-btn,
  .submit-btn {
    width: 100%;
    padding: 10px 20px;
  }
}

/* 加载状态样式 */
.submit-btn.is-loading {
  opacity: 0.8;
  cursor: not-allowed;
}

/* 表单焦点样式优化 */
.form-input .el-input__inner:focus,
.form-textarea .el-textarea__inner:focus {
  outline: none;
}

/* 表单项间距优化 */
.el-form-item:last-child {
  margin-bottom: 0;
}
</style>
